<?php
namespace app\admin\api;

use app\admin\service\PermissionService;
use app\admin\service\RoleService;
use app\admin\validate\RoleValidate;
use think\facade\Request;

class Role extends Base
{
    /**
     * 初始化方法
     *
     * @param  \app\admin\service\RoleService $role
     */
    public function __construct(RoleService $role)
    {
        parent::__construct();

        $this->service = $role;
    }

    /**
     * 接口--获取角色列表
     *
     * @return
     */
    public function getList()
    {
        $data = $this->service->getList();
        return $data;
    }

    /**
     * 接口--删除单条记录操作
     *
     * @return
     */
    public function delete()
    {
        $id = Request::param('id');

        $this->service->destroy($id);

        return ['code'=>0,'msg'=>'删除成功！'];
    }

    /**
     * 新增操作
     *
     */
    public function store(RoleValidate $roleValidate)
    {
        $param = Request::param();

        if(!$roleValidate->check($param)){
            return ['code'=>1,'msg'=>$roleValidate->getError()];
        }

        $id = $this->service->store($param);

       return ['code'=>0,'msg'=>'添加成功','id'=>$id];
    }

    public function read($id)
    {
        $info  = $this->service->getById($id);
        return ['code'=>0,'msg'=>'数据获取成功','data'=>$info];
    }
    /**
     * 更新操作
     *
     */
    public function update(RoleValidate $roleValidate)
    {
        $param = Request::param();

        if(!$roleValidate->check($param)){
            return ['code'=>1,'msg'=>$roleValidate->getError()];
        }

        $this->service->update($param);
        return ['code'=>0,'msg'=>'修改成功'];
    }

    /**
     * 角色权限
     *
     * @param $id
     * @param PermissionService $permissionService
     */
    public function perm($id,PermissionService $permissionService)
    {
        $permissions = $permissionService->getPermissionList();
	foreach ($permissions as $k => $v){
            $v['checked'] = in_array($id,$v->roles->column('id')) ? 1 : 0;
	unset($v['roles']);
            if($v->child){
                foreach ( $v->child as $ko => $vo){
                    $vo['checked'] = in_array($id,$vo->roles->column('id')) ? 1 : 0;
	                unset($vo['roles']);
                    if($vo->child){
                        foreach ( $vo->child as $koo => $voo){
                            $voo['checked'] = in_array($id,$voo->roles->column('id')) ? 1 : 0;
                            unset($voo['roles']);
                        }
                    }
                }
            }
        }
        return ['code'=>0,'msg'=>'获取成功','data'=>$permissions];
    }

    /**
     * 提交角色权限操作
     *
     */
    public function perm_store()
    {
        $data = Request::param();

        $id = $data['id'];

        $perm = $data['perm'];

        $this->service->perm_store($id,$perm);

        cache('rbac_permissions_for_role_id',null);

        return ['code'=>0,'msg'=>'修改成功'];
    }
}
